<template>
  <!-- 登录框 -->
  <div>
    <img src="@/assets/updatePwd.png" width="125" height="125" style="margin-top: 15px">

    <el-form ref="loginForm" :model="form" :rules="rules" label-width="80px" class="login-box">
      <h3 class="login-title">修改账号密码</h3>

      <el-form-item label="原密码" prop="pwd">
        <el-input type="password" placeholder="请输入原密码" show-password v-model="form.pwd"/>
      </el-form-item>

      <el-form-item label="新密码" prop="newPwd">
        <el-input type="password" placeholder="请输入新密码" show-password v-model="form.newPwd"/>
      </el-form-item>

      <el-form-item label="确认密码" prop="newPwd2">
        <el-input type="password" placeholder="请再次输入密码" show-password v-model="form.newPwd2"/>
      </el-form-item>

      <el-form-item id="loginBtn">
        <el-button type="warning" @click="reset">重置</el-button>
        <el-button type="success" @click="onSubmit('loginForm')">确定修改</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>

<script>
export default {
  name: "ChangePwd",
  data() {
    // 将 checkPwd 和 checkSame 提取为独立方法
    var validatePassword = this.checkPwd;
    var validatePasswordMatch = this.checkSame;

    return {
      form: {
        pwd: '',
        newPwd: '',
        newPwd2: ''
      },
      rules: {
        pwd: [
          { required: true, message: "原密码不可为空", trigger: "blur" },
          { validator: validatePassword, trigger: "submit" }
        ],
        newPwd: [
          { required: true, message: "新密码不可为空", trigger: "blur" }
        ],
        newPwd2: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          { validator: validatePasswordMatch, trigger: "blur" }
        ],
      }
    };
  },
  methods: {
    checkPwd(rule, value, callback) {
      const token = localStorage.getItem('token');
      this.$axios({
        url: '/user/pwdCheck',
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        data: {
          pwd: this.form.pwd
        }
      }).then(res => {
        if (res.data === false) {
          callback(new Error('原密码不正确'));
        } else {
          callback();
        }
      }).catch(error => {
        callback(new Error('请求失败'));
      });
    },

    checkSame(rule, value, callback) {
      if (value !== this.form.newPwd) {
        callback(new Error('两次密码不一致'));
      } else {
        callback();
      }
    },

    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 验证通过后，首先检查原密码
          this.checkPwd(null, this.form.pwd, (error) => {
            if (!error) {
              const token = localStorage.getItem('token');
              // 原密码正确后，继续发送修改密码请求
              this.$axios({
                method: 'patch',
                url: '/user/updatePwd',
                headers: {
                  'Authorization': `Bearer ${token}`,
                  'Content-Type': 'application/json'
                },
                data: {
                  old_pwd: this.form.pwd,
                  new_pwd: this.form.newPwd,
                  re_pwd: this.form.newPwd2
                }
              }).then((res) => {
                if (res.data.code === 200) {
                  this.$router.push('/');
                  const h = this.$createElement;
                  this.$notify({
                    title: '修改成功',
                    message: h('i', { style: 'color: teal' }, '请重新登录'),
                    type: 'success'
                  });
                } else {
                  this.$notify({
                    title: '修改失败',
                    message: res.data.message || '修改密码失败，请重试。',
                    type: 'error'
                  });
                }
              }).catch((error) => {
                this.$notify({
                  title: '修改失败',
                  message: error.response ? error.response.data.message : '修改密码失败，请重试。',
                  type: 'error'
                });
              });
            }
          });
        } else {
          return false;
        }
      });
    },

    reset() {
      this.form.pwd = '';
      this.form.newPwd = '';
      this.form.newPwd2 = '';
    }
  }
}
</script>

<style scoped>
.login-box {
  border: 1px solid #DCDFE6;
  width: 400px;
  height: 300px;
  margin: 20px auto;
  padding: 35px 40px 20px 20px;
  border-radius: 5px;
  box-shadow: 0 0 25px #f5efef;
  background-color: #ffffff;
}

.login-title {
  text-align: center;
  margin: 0 auto 40px 20px;
  color: #303133;
}

#loginBtn {
  margin-left: -50px;
}
</style>
